var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');
var cheerio = require('cheerio');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

function main(options) {

    var ipList = [];
    var ipIndex = 0;
    var proxy = '';

    var offset = options.offset;
    var artist;
    var albumList = [];

    function changeIp() {
        if (ipIndex < ipList.length - 1) {
            ipIndex += 1;
        } else {
            ipIndex = 0;
        }
        setProxy();
    }

    function setProxy() {
        var item = ipList[ipIndex];
        console.log(item);

        var ip = item.ip;
        var port = item.port;

        proxy = `http://${ip}:${port}`;
        console.log('proxy');

        console.log(proxy);

    }


    function getIpList() {
        var connection1 = mysql.createConnection(mysqlProxy);
        var query1 = 'select * from ip_table1 where success_count>=6 order by success_count desc';
        connection1.connect();
        connection1.query(query1, function (err, res) {
            if (err) {
                console.log('query1 error');
                console.log(err);

            } else {
                ipList = res;
                // console.log(ipList);

                // console.log(ipList.length);
                setProxy();
                getArtist();
            }
        });
        connection1.end();
    }
    getIpList();

    function getArtist() {
        var connection = mysql.createConnection(mysqlCloudMusic);
        var queryString = 'select * from artist order by album_version limit 1 offset ' + offset;

        connection.query(queryString, function (err, res) {
            console.log(queryString);
            
            if (err) {
                console.log('query2 err');
                console.log(err);

            } else {
                if (res.length === 0) {
                    console.log('no artist');
                    setTimeout(() => {
                        getArtist();
                    }, 3600 * 1000);
                } else {
                    artist = res[0];
                    console.log(artist);
                    
                    console.log(artist);
                    getAlbum({});
                }
            }
        });
        connection.end();
    }

    function getAlbum(options) {
        const artistId = artist.id;
        let url = `https://music.163.com/artist/album?id=${artistId}`;
        if (options.url) {
            url = options.url;
        }
        superagent.get(url)
            .timeout(5000)
            // .proxy(proxy)
            .end(function (err, res) {
                console.log(url);
                if (err) {
                    console.log(err);
                    
                    console.log('http error');
                    console.log(proxy);
                    console.log();
                    changeIp();
                    getArtist();
                    
                } else {
                    console.log('http success');
                    // fs.writeFile(`html/album-${artistId}.html`, res.text, function () { })

                    var text = res.text;
                    if(/很抱歉，你要查找的网页找不到/g.test(text)){
                        console.log('很抱歉，你要查找的网页找不到');
                        // setTimeout(() => {
                        //     offset+=1;
                        //     changeIp();
                        //     getArtist();
                        // }, 300);
                        feedback()
                    }else{

                        if ((/暂无专辑/g).test(text)) {
                            feedback();
                            // fs.writeFile('html/album1.html', text, function () { })
                        } else if (/很抱歉，服务器开小差了，请稍后再试/g.test(text)) {
                            console.log('很抱歉，服务器开小差了，请稍后再试');
                            console.log(proxy);
                            console.log();
                            // fs.writeFile('html/album2.html', text, function () { })
                            setTimeout(() => {
                                changeIp();
                                getArtist();
                            }, 300);
                        } else {
    
                            var $ = cheerio.load(text);
    
                            var m_song_module = $('#m-song-module');
                            // fs.writeFile('html/album3.html', text, function () { })
    
                            var list2 = m_song_module.find('li');
                            console.log(list2.length);
                            if (list2.length > 0) {
                                list2.each((i, element) => {
                                    var item = list2.eq(i);
                                    var name = item.find('p').eq(0).text().replace(/\n/g, '');
                                    console.log(name);
                                    var id = item.find('p>a').eq(0).attr().href.replace(/\/album\?id=/g, '');
                                    console.log(id);
                                    var time = item.find('p').eq(1).text();
    
                                    var value = [id, name, artistId, time];
                                    console.log(value);
                                    albumList.push(value);
                                });
                                console.log(albumList);
    
                                var u_page = $('.u-page');
                                if (u_page.length > 0) {
                                    console.log('u-page >0');
                                    var znxt = $('.znxt').eq(0);
                                    var href = znxt.attr().href;
                                    var url2;
                                    if (href.match(/javascript.?/g)) {
                                        // fn3();
                                        var albumListLength = albumList.length;
                                        if (albumListLength > 0) {
                                            upload();
                                        } else {
                                            feedback();
                                        }
                                    } else {
                                        options.url = 'https://music.163.com' + znxt.attr().href;
                                        console.log(url);
                                        getAlbum(options);
                                    }
                                } else {
                                    var albumListLength = albumList.length;
                                    if (albumListLength > 0) {
                                        upload();
                                    } else {
                                        feedback();
                                    }
                                }
                            } else {
                                setTimeout(() => {
                                    changeIp();
                                    getArtist();
                                }, 300);
                            }
                        }
                    }


                }
            })
    }

    function upload() {
        // console.log(albumList);

        var connection = mysql.createConnection(mysqlCloudMusic);
        var queryString = "insert ignore into album(id, name, artist_id, time) values ?";
        connection.connect();

        connection.query(queryString, [albumList], function (err, res) {
            if (err) {
                console.log(err);
                getArtist();
            } else {
                console.log('upload成功');

                console.log(res);
                console.log();

                feedback();
            }
        });
        connection.end();
    }
    function feedback() {
        const artistId = artist.id;

        var connection4 = mysql.createConnection(mysqlCloudMusic);

        var album_version = 1;
        if (artist.album_version) {
            album_version = artist.album_version + 1;
        }
        var query4 = `UPDATE artist   
         SET album_version=${album_version} where id =${artistId};`
        console.log(query4);
        connection4.query(query4, function (err, res) {
            if (err) {
                console.log('query4 err');

            } else {
                console.log('query4 res');
                setTimeout(() => {
                    getArtist();
                    // fs
                }, 2000);
            }
        });
        connection4.end();

    }
}

for (var i = 0; i < 1; i++) {
    const offset = 10 * i;
    main({
        offset: offset
    });
}